package com.demo.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.core.exception.ParameterException;
import com.demo.dao.RegistrationInformationDao;
import com.demo.dao.TeamCompositionDao;
import com.demo.dao.UserDao;
import com.demo.domain.RegistrationInformation;
import com.demo.domain.TeamComposition;
import com.demo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuthorityUtils {
    @Autowired
    private TeamCompositionDao teamCompositionDao;

    @Autowired
    private RegistrationInformationDao registrationInformationDao;

    @Autowired
    private UserDao userDao;

    /**
     * 验证当前用户是否有修改队伍信息的权限(只有队长喝指导老师有权)
     *
     * @param tpId
     * @param uid
     * @return
     */
    public boolean qualifiedToModify(Long tpId, Long uid) {
        if (tpId != null && tpId > 0l && uid != null && uid > 0l) {
            //设置查询条件
            LambdaQueryWrapper<TeamComposition> compositionWrapper = new LambdaQueryWrapper<>();
            compositionWrapper.eq(TeamComposition::getTeamId, tpId);
            compositionWrapper.eq(TeamComposition::getUid, uid);
            //查询队伍
            TeamComposition teamComposition = teamCompositionDao.selectOne(compositionWrapper);
            return teamComposition != null &&
                    (teamComposition.getMemberType() == 0 || teamComposition.getMemberType() == 1) ?
                    true : false;
        }
        return false;
    }


    /**
     * 检测是否有存在RegistrationInformation记录可以修改
     * （根据riId,uid匹配且该申请只能为未审核的状态）
     *
     * @param riId
     * @param uid
     * @return
     * @throws ParameterException
     */
    public boolean isQualifyToModifyRegistration(Long riId, Long uid) throws ParameterException {
        if (riId == null || riId < 0l) {
            throw new ParameterException("riId为空或值非法");
        }
        if (uid == null || uid < 0l) {
            throw new ParameterException("uid为空或值非法");
        }
        //检查当前申请是否有修改权限（申请人是否为该账户）(用RiId,Uid,RiReviewStatus进行匹配)
        LambdaQueryWrapper<RegistrationInformation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RegistrationInformation::getRiId, riId)
                .eq(RegistrationInformation::getRiUid, uid)
                .eq(RegistrationInformation::getRiReviewStatus, 0);
        //只有未审核的申请可以修改
        Long count = registrationInformationDao.selectCount(wrapper);
        return count != null && count > 0l ? true : false;
    }

    /**查询当前数据库是否有该账号的用户
     *
     * @param uid
     * @return
     * @throws ParameterException
     */
    public Boolean haveUser(Long uid) throws ParameterException {
        if (uid == null || uid < 0l) {
            throw new ParameterException("uid错误");
        }
        //确认数据库中是否有当前账户
        User user = userDao.selectById(uid);
        return user != null ? true : false;
    }
}
